#coding=utf-8
import json
import sys
import os
import  re
import shutil
from os.path import walk, join, normpath 
viewTemplete = "";
createViewDir = "";
def file_extension(path): 
	return os.path.splitext(path)[1] 
def createAutoScript(dirfull):
	for root, dirs, files in os.walk(dirfull):
		for file in files:
			if file_extension(file) == ".json":
				fileName = os.path.splitext(file)[0];
				prePath = root[root.find("res\\")+4:len(root)];
				replaceTxt(os.path.join(root,file),viewTemplete,os.path.join(createViewDir,fileName+".js"),"Templet",fileName)
				print "自动生成界面代码======================>".decode('utf-8').encode(sys.getfilesystemencoding()),fileName
				createBaseView(fileName)
#是否可以创建属性
def canCreateProperty(proName):
	#是否是按钮
	if(proName.find("btn_") == 0):
		return True;
	#是否是图片
	if(proName.find("img_") == 0):
		return True;
	#是否是精灵
	if(proName.find("sp_") == 0):
		return True;
	#是否是输入框
	if(proName.find("input_") == 0):
		return True;
	#是否是列表
	if(proName.find("listview") == 0):
		return True;
	#是否是文本
	if(proName.find("lbt_") == 0):
		return True;
	#是否是checkbox
	if(proName.find("cb_") == 0):
		return True;
	#是否是slider
	if(proName.find("slider_") == 0):
		return True;
	#是否是node
	if(proName.find("node_") == 0):
		return True;
	#是否是panel
	if(proName.find("panel_") == 0):
		return True;
	#是否是ani
	if(proName.find("ani_") == 0):
		return True;
	return False;
def createPropertys(path):
	lines = open(path).readlines();
	respath = path[path.find("res\\"):len(path)];
	respath = respath.replace("\\","/");
	content = "var layer = this.initLayer(\""+respath+"\");\n"
	for s in lines:
		str = "\"Name\": \"";
		index = s.find(str);
		if(index != -1):
			proName = s[index+len(str):len(s)-3];
			if(canCreateProperty(proName)):
				content += "\t\tthis."+proName+" = CCSHelper.seekNodeByName(layer,\""+proName+"\");\n";
	return content;
def createViewButtonFuncs(path):
	lines = open(path).readlines();
	content = "var self = this;\n";
	for s in lines:
		str = "\"Name\": \"";
		index = s.find(str);
		if(index != -1):
			proName = s[index+len(str):len(s)-3];
			if(proName.find("btn_") == 0):
				content += createViewSigleButtonFunc(proName);
	return content;
def createViewSigleButtonFunc(btnName):
	funcname = "press"+btnName[btnName.find("btn_")+4:len(btnName)];
	content = "\t\tvar "+funcname+" = function(btn)\n";
	content += "\t\t{\n";
	content += "\t\t\tif (self."+funcname+")\n";
	content += "\t\t\t{\n";
	content += "\t\t\t\tself."+funcname+"(btn);\n";
	content += "\t\t\t}\n";
	content += "\t\t}\n";
	content += "\t\tTouchManager.registBtnEvent(this."+btnName+","+funcname+",BUTTON_TYPE.SCALE);\n";
	return content;
def createViewClassBtnFuncs(path):
	lines = open(path).readlines();
	content = "";
	for s in lines:
		str = "\"Name\": \"";
		index = s.find(str);
		if(index != -1):
			proName = s[index+len(str):len(s)-3];
			if(proName.find("btn_") == 0):
				content += createViewClassSigleBtnFunc(proName);
	return content;
def createViewClassSigleBtnFunc(btnName):
	funcname = "press"+btnName[btnName.find("btn_")+4:len(btnName)];
	content = "\t"+funcname+" : function(btn)\n";
	content += "\t{\n";
	content += "\t\tif (this._super)\n";
	content += "\t\t{\n";
	content += "\t\t\tthis._super(btn)\n";
	content += "\t\t}\n";
	content += "\t},\n";
	return content;
def createViewName(viewName):
	content = "this.setViewName(\""+viewName+"\");";
	return content;
def replaceTxt(resFile,orgfile,outputFile,orgtxt,replacetxt):
	viewName = createViewName(replacetxt);
	propertys = createPropertys(resFile);#创建属性
	viewbtnFuncs = createViewButtonFuncs(resFile);#创建按钮事件
	viewClassbtnFuncs = createViewClassBtnFuncs(resFile);#创建按钮事件
	if os.path.isfile(outputFile):
		orgfile = outputFile
	lines = open(orgfile).readlines()  #打开文件，读入每一行
	fp = open(outputFile,'w')  #打开你要写得文件
	for s in lines:
		line = s;
		if(s.find(orgtxt) != -1):
			line = line.replace(orgtxt,replacetxt);
		if(s.find("//view_name") != -1):
			line = line.replace("//view_name",viewName);
		if(s.find("//view_ui_propertys") != -1):
			line = line.replace("//view_ui_propertys",propertys);
		if(s.find("//view_class_btn_evnets") != -1):
			line = line.replace("//view_class_btn_evnets",viewClassbtnFuncs);
		if(s.find("//view_btn_events") != -1):
			line = line.replace("//view_btn_events",viewbtnFuncs);
		fp.write(line);
	fp.close()  # 关闭文件
def removeAutoTxt(filename):
	lines = open(filename).readlines()  #打开文件，读入每一行
	fp = open(filename,'w')  #打开你要写得文件
	canAdd = True
	for s in lines:
		line = s;
		if(s.find("create view name begin") != -1):
			fp.write(line);
			fp.write("\n\t\t//view_name\n");
			canAdd = False
		if(s.find("create view name end") != -1):
			canAdd = True
		if(s.find("create view ui propertys begin") != -1):
			fp.write(line);
			fp.write("\n\t\t//view_ui_propertys\n");
			canAdd = False
		if(s.find("create view ui propertys end") != -1):
			canAdd = True
		if(s.find("create view btn events begin") != -1):
			fp.write(line);
			fp.write("\n\t\t//view_btn_events\n");
			canAdd = False
		if(s.find("create view btn events end") != -1):
			canAdd = True
		if(s.find("create view class btn evnets begin") != -1):
			fp.write(line);
			fp.write("\n//view_class_btn_evnets\n");
			canAdd = False
		if(s.find("create view class btn evnets end") != -1):
			canAdd = True
		if(canAdd):
			fp.write(line);
	fp.close()  # 关闭文件
def removeAutoScript(dirfull):
	for root, dirs, files in os.walk(dirfull):
		for file in files:
			if file_extension(file) == ".js":
				fileName = os.path.splitext(file)[0];
				prePath = root[root.find("res\\")+4:len(root)];
				removeAutoTxt(os.path.join(root,file))
def createBaseView(viewName):
	baseViewDir = os.path.join(sys.path[0],"..\\src\\View");
	if not os.path.isdir(baseViewDir):
		os.makedirs(baseViewDir,0777)
	baseViewTemplete = os.path.join(sys.path[0],"..\\..\\ViewTemplet\\Base_TempletView.js");
	baseViewName = "Base_"+viewName
	baseViewFile = os.path.join(baseViewDir,baseViewName+".js");
	if not os.path.isfile(baseViewFile):
		lines = open(baseViewTemplete).readlines()  #打开文件，读入每一行
		fp = open(baseViewFile,'w')  #打开你要写得文件
		for line in lines:
			if(line.find("Templet") != -1):
				line = line.replace("Templet",viewName);
			fp.write(line);
		fp.close()  # 关闭文件
		print "自动生成界面代码基类======================>".decode('utf-8').encode(sys.getfilesystemencoding()),baseViewName
#入口
if __name__=="__main__":
	dirname = os.path.join(sys.path[0],"res")
	createViewDir = os.path.join(sys.path[0],"src\\View");
	viewTemplete = os.path.join(sys.path[0],"..\\..\\ViewTemplet\\TempletView.js");
	if not os.path.isdir(createViewDir):
		os.makedirs(createViewDir,0777)
	print "======================自动生成代码开始======================".decode('utf-8').encode(sys.getfilesystemencoding())
	# 先删除自动生成的
	removeAutoScript(createViewDir)
	# 生成新的代码
	createAutoScript(dirname)
	print "======================自动生成代码结束======================".decode('utf-8').encode(sys.getfilesystemencoding())
	print "点击回车键退出".decode('utf-8').encode(sys.getfilesystemencoding())
	raw_input()

